<?php
namespace app\index\controller;

use app\common\controller\Base;
use think\Db;
use app\common\model\StateChange;
use think\Cookie;
use GuzzleHttp\json_encode;

class User extends Base
{
    protected $state;

    protected $beforeActionList = [
        '_if_login' => ['except' => 'register,getAward,service,registerExist,recharge'],
    ];


    /**未登录**/
    protected function _if_login()
    {
        if (!$this->user_all['id']) {
            js_tishi('请先登录账号！', '/');
            exit;
        }
    }


    public function _initialize()
    {
        parent::_initialize();
        //用户中心所需参数
        $start = array(
            'user_all' => $this->user_all,
            'logo' => $this->logo,
            'app_down' => $this->app_down,
            'now_time_windows' => $this->now_time_windows,
            'usnameclass' => $this->usnameclass
        );
        $f = Db::name('username')->where('username', $this->user_all['username'])->find();
        $this->assign('f', $f);
        $open = Db::name('agent_off')->where('id', 1)->value('open');
        $this->assign('open', $open);
        $this->state = new StateChange();
        $this->assign($start);
    }

    /**
     * @Author
     * @Purpose 电脑版用户中心首页
     * @Time 2017-11
     */
        public function index()
    {
        $us = input('us') ? input('us') : 'i';
        $res = Db::name('username')->where('username', $this->user_all['username'])->find();
        $query = Db::name('username')->alias('a')->join('__BANK__ b','b.id=a.bankname')->field('a.*,b.bankname as bank')->where('a.username', $this->user_all['username'])->find();
        $this->assign('query',$query);
        $this->assign('res', $res);
        $this->assign('header', $res['img']);

        /**
         * @todo 等级分析
         */
        $level = Db::name("us_class")->field("id,class_name,czl,xml")->order("czl asc")->select();
        $current_level_id = $res['us_class'];
        $next_level = "";
        $next_money = 0;
        $next_xml = 0;
        foreach($level as $k=>$v){
            if( $current_level_id==$v['id'] && isset($level[$k+1]) ){
                $next_level = $level[$k+1]['class_name'];
                $next_money = ceil( floatval($level[$k+1]['czl'])-floatval($res['czzje']) );
                $next_xml = ceil( floatval($level[$k+1]['xml'])-floatval($res['tzzje']) );
                break;
            }
        }
        $this->assign('next_level',$next_level);
        $this->assign('next_money',$next_money);
        $this->assign('next_xml',$next_xml);

        /* ------------------------------------------------安全中心----------------------------------------------- */
        if ($us == 'i') {
            $bank = Db::name('bank')->select();
            $this->assign('bank', $bank);
            $this->assign('current', 'index');
            return $this->fetch('index');
        }
        /* ------------------------------------------------安全信息----------------------------------------------- */
        if ($us == 'q') {
            $query = Db::name('rizhi_jl')->where('rz_user', $this->user_all['username'])->order('id', 'DESC')->select();
            if (!isset($query[0])) $query[0] = array('rz_time' => time(), 'rz_ip' => '');
            if (!isset($query[1])) $query[1] = array('rz_time' => time(), 'rz_ip' => '');

            $position = array();
            $ip = @file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip={$query[0]['rz_ip']}");

            if ($ip) {
                $ip = json_decode($ip, true);
                $position[1] = $ip['data']['region'] . ' ' . $ip['data']['city'];
            }
            $ip2 = @file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip={$query[1]['rz_ip']}");
            if ($ip2) {
                $ip2 = json_decode($ip2, true);
                $position[2] = $ip2['data']['region'] . ' ' . $ip2['data']['city'];
            }
            $this->assign('position', $position);
            $this->assign('query', $query);
            return $this->fetch('usersure');
        }
        /* ------------------------------------------------个人资料----------------------------------------------- */
        if ($us == 'r') {

            return $this->fetch('userziliao');
        }
    }

    public function shenqing()
    {
        $user = Db::name('username')->where('username', $this->user_all['username'])->value('dlshstatus');
        $this->assign('user', $user);
        return $this->fetch();
    }

    public function shenqinganniu()
    {
        $data['dlshstatus'] = 1;
        if (Db::name('username')->where('username', $this->user_all['username'])->update($data)) {
            js_tishi('已提交审核', 'index');
        } else {
            js_tishi('已提交过审核，请耐心等待', 'index');
        }
    }

    /**
     * 修改密码
     * @param string $oldpass
     * @param string $pass
     * @param string $repass
     */
    public function updatePwd()
    {
    	$oldpass = input('oldpass');
    	$pass = input('pass');
    	$repass = input('repass');
        if (strlen($pass) < 6) {
            js_tishi('密码长度至少为6位！', '/index/user/index');
            exit;
        }
        if ($oldpass != '' && $pass != '' && $repass != '') {
            if ($repass == $pass && $oldpass != $repass) {
                $res = Db::name('username')->where('username', $this->user_all['username'])->find();
                if ($res['id']) {
                    if ($res['password'] == md5($oldpass)) {
                        $data = array('password' => md5($repass));
                        $query = Db::name('username')->where('username', $this->user_all['username'])->update($data);
                        return 1;
                    }
                }
            }
        }else{
        	return 0;
        }
    }

    public function emdPwd()
    {
        if (input('post.real_name') != '' && input('post.pass') != '') {
            
            if (strlen(input('post.pass')) == 6) {
                $res = Db::name('username')->where('username', $this->user_all['username'])->find();
                if ($res['id']) {
                    if ($res['ejmm'] == '') {
                        $data = array('bankren' => input('post.real_name'), 'ejmm' => md5(input('post.pass')));
                        $query = Db::name('username')->where('username', $this->user_all['username'])->update($data);
                        if($query){
                            js_tishi('设置成功', 'index');
                        }
                    } else {
                    	$length=strlen(input('post.pass_new'));
                    	if($length!="6"){exit(json_encode("密码必须是6位数字"));}
                        if ($res['ejmm'] == md5(input('post.pass'))) {
                            $data = array('ejmm' => md5(input('post.pass_new')));
                            $result=Db::name('username')->where('username', $this->user_all['username'])->update($data);
                            if($result){
                                exit(json_encode("修改成功"));
                            }else{
                                exit(json_encode("修改失败"));
                            }
                            
                        } else {
                           exit(json_encode("旧密码输入错误"));
                            
                        }
                    }
                }
            } else {
                exit(json_encode("密码必须是6位数字"));
            }
        } else {
            exit(json_encode("请输入完整信息"));
        }
    }

    public function banksz($bank_id = '', $bank_account = '', $bank_address = '', $pass = '',$bank_sf="",$bank_sq="",$bank_ren="")
    {
        if ($bank_id != '' && $bank_account != '' && $bank_address != '' && $pass != '') {

            $count = Db::name("username")->where(['bankno'=>$bank_account])->count();
            if( $count > 0 ){
                js_tishi('您已注册有蚂蚁赢彩账户，请咨询客服帮助找回！', '/index/user/index');
                exit;
            }

            $res = Db::name('username')->where('username', $this->user_all['username'])->find();
            if ($res['id']) {
//                if ($res['ejmm'] != md5($pass)) {
//                    js_tishi('资金密码错误！', '/index/user/index');
//                    exit;
//                }
                $t = Db::name('xt_caijin')->where('id', 1)->find();
                if ($t['open'] == 0) {
                    $je = $t['je'];
                    $dml = $t['cj_dml'];
                } else {
                    $je = 0;
                    $dml = 0;
                }
                $jes = $je + $res['je'];
                $dml = $dml + $res['dml'];
                $zcj = $res['zcjje']+$je;
                
                $data = array('bankname' => $bank_id,'bankren'=>$bank_ren,'ejmm'=>md5($pass),'zcjje'=>$zcj,'bankno' => $bank_account, 'bank_zhihang' => $bank_address, 'je' => $jes, 'dml' => $dml, 'reg_je' => $je, 'bk_time' => time(),'banksf'=>$bank_sf,'banksq'=>$bank_sq);
                	
                $quer = Db::name('username')->where('username', $this->user_all['username'])->update($data);
                if ($jes > 0) {
                	Db::name('bank_caijin')->insert(array('username'=>$this->user_all['username'],'bankje'=>$je,'yue'=>$res['je'],'time'=>time(),'hqfs'=>$t['open']));
                	$this->state->UserFaSong($res['username'], "您已绑定银行卡，赠送彩金：" . $je . "元。已到账，请注意查收！");
                    $datas = array(
                        'username'=>$this->user_all['username'],
                        'user_class'=>$res['us_class'],
                        'cjje'=>$je,
                        'fstime'=>time(),
                        'beizhu' => '系统赠送，用户绑定银行卡，赠送彩金',
                        'czadmin' => '绑卡赠送彩金',
                        'cjhje'=>$jes,
                    );
                    Db::name('caijin_list')->insert($datas);
                }
                if($quer){
                	js_tishi('设置成功', '/index/user/index');
                }
            }
        } else {
            js_tishi('信息不完整', '/index/user/index');
        }
    }

    public function mobileqq($user_qq = '', $contact_info = '', $user_mobile = '')
    {
        if ($user_qq != '') {
            $res = Db::name('username')->where('username', $this->user_all['username'])->find();
            if ($res['id']) {
                $data = array('qq' => $user_qq);
                $query = Db::name('username')->where('username', $this->user_all['username'])->update($data);
                js_tishi('设置成功', '/index/user/index');
            }
        } else {
            js_tishi('请填写有效的信息', '/index/user/index');
        }
    }

    /**
     * 赔率详情
     * @return Ambigous <\think\mixed, string>
     */
    public function peilvdetail()
    {
        //all classes
        $lottery_fenlei = Db::name('lottery_classify')->where('status', 1)->select();

        //one class
        $lottery_category_id = input('lottery_category_id', 1);
        $lottery = Db::name('lottery_classify')->where(['id' => $lottery_category_id, 'status' => 1])->field('id, fandian')->find();

        //odds
        $peilv = Db::name('peilv')->where(['lottery_class_id' => $lottery['id'], 'ifopen' => 1])->select();
        foreach ($peilv as &$v) {
            if ($v['spare']){
                $v['peilv_name'] = $v['spare'] . '_' . $v['peilv_name'];
            }
        }

        $this->assign('lottery', $lottery);
        $this->assign('peilv', $peilv);
        $this->assign('lottery_id', $lottery_category_id);
        $this->assign('caipiao', $lottery_fenlei);
        return $this->fetch();
    }

    public function caiwu(){
        //开始处理充值
        if ($this->user_all['swzh'] == 1) {
            js_tishi('试玩账号无法充值！', '/index/User/index');
            exit;
        }
        //线下账户列表
        $res = Db::name('pay_xxlist')->select();
        foreach ($res as $v) {
            $data[$v['xx_remark']][] = $v;
        }
        //线上二维码账户列表
        $res = Db::name('code_account')->where('lock', 0)->select();
        foreach ($res as $v) {
            $online_ac[$v['type']][] = $v;
        }

        $username = $this->user_all['username'];
        $pay_type_gt = Db::name('pay_type_list')->where(['method' => 1, 'pc' => 1])->order('order', 'DESC')->column('type_name', 'type_value');
        $pay_type_sf = Db::name('pay_type_list')->where(['method' => 2, 'pc' => 1])->order('order', 'DESC')->column('type_name', 'type_value');
        $pay_type_kf = Db::name('pay_type_list')->where(['method' => 5, 'pc' => 1])->order('order', 'DESC')->column('type_name', 'type_value');
        $info = Db::name('pay_xianshang')->field('id,pay_name,open,level')->select();
        foreach ($info as &$v) {
            $v['level_open'] = 0;
            $level_arr = explode(',', $v['level']);
            if (in_array($this->user_all['us_class'], $level_arr)) $v['level_open'] = 1;
        }
        $this->assign('info', $info);
        $this->assign('username', $username);
        $this->assign('pay_type_gt', $pay_type_gt);
        $this->assign('pay_type_sf', $pay_type_sf);
        $this->assign('pay_type_kf', $pay_type_kf);
        $this->assign('time', time());
        $this->assign('current', 'deposit');
        $this->assign('ali', $data['ali'][0]);
        $this->assign('weixin', $data['wechat'][0]);
        $this->assign('bank', $data['bank'][0]);
        $this->assign('data', $data);
        $this->assign('online_ac', $online_ac);
        return $this->fetch();
    }

    /**
     * @Author
     * @Purpose 电脑版用户充值
     * @Time 2017-11-20
     */
    public function recharge(){
        //开始处理充值
        $user = $this->user_all;
        if (!$user['id']) {
            js_tishi('请先登录账号！', '/');
            exit;
        }
        if ( 1==intval($user['swzh']) ) {
            js_tishi('试玩账号无法充值！', '/index/User/index');
            exit;
        }
        $method_list = Db::name("pay_method")->where(['status'=>1])->order("seq asc")->select();
        $this->assign('method_list',$method_list);
//        $first_method = '';
//        if( !empty($method_list) ){
//            $first_method = $method_list[0];
//        }
//
//        $bank_list = array();
//        if( !empty($first_method) ){
//            $level = $user['us_class'];
//            //线上第三方
//            $onBand = Db::name('pay_type_list')->alias("a")
//                ->join("__PAY_XIANSHANG__ b",'a.method=b.id','LEFT')
//                ->where(['a.method_id'=>$first_method['id'],'a.pc'=>1,'b.open'=>1])
//                ->field("a.id,b.pay_name,a.type_name,a.type_value ,b.level,1 as method, 0 as controller")
//                ->select();
//            foreach( $onBand as $k=>$v ){
//                $levelAttr = explode(',',$v['level']);
//                $onBand[$k]['controller'] = ChineseToPY($v['pay_name']);
//                unset($onBand[$k]['level']);
//                if( !in_array($level,$levelAttr) ) unset($onBand[$k]);
//            }
//            //线上支付宝或微信
//            $onThird = Db::name("pay_xianshang")->where(['open'=>1,'is_code'=>1])->field("id,pay_name,level,0 as type_value,2 as method,0 as controller")->select();
//            $hasUser = Db::name("code_account")->where(['method_id'=>$first_method['id']])->group("type")->column("type,count(*) as num");
//            foreach( $onThird as $k=>$v ){
//                $user_key = $v['pay_name']=="微信扫码" ? "wechat" : 'alipay';
//                if( !isset($hasUser[$user_key]) && empty($hasUser[$user_key]) ){
//                    unset($onThird[$k]);
//                    continue;
//                }
//                $levelAttr = explode(',',$v['level']);
//                unset($onThird[$k]['level']);
//                if( !in_array($level,$levelAttr) ){
//                    unset($onThird[$k]);
//                    continue;
//                }
//            }
//            //线下支付
//            $offThird = Db::name("pay_xxlist")->where(['method_id'=>$first_method['id']])->field("id,xx_name as type_name,0 as type_value,xx_weixin,xx_zhifubao,xx_wangyin,3 as method,0 as controller")->select();
//            foreach($offThird as &$v){
//                if( 1==intval($v['xx_weixin']) ) $v['pay_name'] = '微信';
//                if( 1==intval($v['xx_zhifubao']) ) $v['pay_name'] = '支付宝';
//                if( 1==intval($v['xx_wangyin']) ) $v['pay_name'] = '银联';
//                unset($v['xx_weixin']);
//                unset($v['xx_zhifubao']);
//                unset($v['xx_wangyin']);
//            }
//            unset($v);
//            $bank_list = array_merge($onBand,$onThird,$offThird);
//        }
//        $this->assign('bank_list',$bank_list);
//
//        $first_bank = '';
//        if( !empty($bank_list) ){
//            $first_bank = $bank_list[0];
//        }
//        //默认第一个支付方案。method:1(第三方),2(线上),3(线下)
//        $this->assign('bank',$first_bank);
//        $this->assign('time',time());
//        $this->assign('name',$user['username']);
        return $this->fetch();
    }
    public function rechargeDetail(){
        $user = $this->user_all;
        if (!$user['id']) {
            js_tishi('请先登录账号！', '/');
            exit;
        }
        if ( 1==intval($user['swzh']) ) {
            js_tishi('试玩账号无法充值！', '/index/User/index');
            exit;
        }

        $id = input('id',0);
        if( empty($id) ){
            js_tishi('无效方案！', '/index/User/recharge');
            exit;
        }
        $level = $user['us_class'];
        //线上第三方
        $onBand = Db::name('pay_type_list')->alias("a")
            ->join("__PAY_XIANSHANG__ b",'a.method=b.id','LEFT')
            ->where(['a.method_id'=>$id,'a.pc'=>1,'b.open'=>1])
            ->field("a.id,b.pay_name,a.type_name,a.type_value ,b.level,1 as method, 0 as controller")
            ->order('a.order','DESC')
            ->select();
        foreach( $onBand as $k=>$v ){
            $levelAttr = explode(',',$v['level']);
            $onBand[$k]['controller'] = ChineseToPY($v['pay_name']);
            unset($onBand[$k]['level']);
            if( !in_array($level,$levelAttr) ) unset($onBand[$k]);
        }
        //线上支付宝或微信

        $onThird = Db::name("pay_xianshang")->where(['open'=>1,'is_code'=>1])->field("id,pay_name,level,0 as type_value,2 as method,0 as controller")->order('order','DESC')->select();
        $hasUser = Db::name("code_account")->where(['method_id'=>$id])->group("type")->column("type,count(*) as num");
        foreach( $onThird as $k=>$v ){
            $user_key = $v['pay_name']=="微信扫码" ? "wechat" : 'alipay';
            if( !isset($hasUser[$user_key]) && empty($hasUser[$user_key]) ){
                unset($onThird[$k]);
                continue;
            }
            $levelAttr = explode(',',$v['level']);
            unset($onThird[$k]['level']);
            if( !in_array($level,$levelAttr) ) unset($onThird[$k]);
        }
        //线下支付
        $offThird = Db::name("pay_xxlist")->where(['method_id'=>$id,'status'=>1])->field("id,xx_name as type_name,0 as type_value,xx_weixin,xx_qq,xx_zhifubao,xx_wangyin,3 as method,0 as controller")->select();
        foreach($offThird as &$v){
            if( 1==intval($v['xx_weixin']) ) $v['pay_name'] = '微信扫码';
            if( 1==intval($v['xx_zhifubao']) ) $v['pay_name'] = '支付宝扫码';
            if( 1==intval($v['xx_wangyin']) ) $v['pay_name'] = '银联转账';
            if( 1==intval($v['xx_qq']) ) $v['pay_name'] = 'QQ扫码';
            unset($v['xx_weixin']);
            unset($v['xx_zhifubao']);
            unset($v['xx_wangyin']);
            unset($v['xx_qq']);
        }
        unset($v);
        $bank_list = array_merge($onBand,$onThird,$offThird);
        if( empty($bank_list) ){
            js_tishi('无支付方案！', '/index/User/recharge');
            exit;
        }
        $this->assign('list',$bank_list);
        $this->assign('name',$user['username']);
        return $this->fetch('recharge_detail');
    }
    /**
     * 切换支付方案时，获取新信息列表
     */
    public function getPayMethodDetail(){
        $id = input('post.id',0);
        if( empty($id) ) return json_encode(['status'=>0,'msg'=>'无效方案']);
        $user = $this->user_all;
        $level = $user['us_class'];
        //线上第三方
        $onBand = Db::name('pay_type_list')->alias("a")
            ->join("__PAY_XIANSHANG__ b",'a.method=b.id','LEFT')
            ->where(['a.method_id'=>$id,'a.pc'=>1,'b.open'=>1])
            ->field("a.id,b.pay_name,a.type_name,a.type_value ,b.level,1 as method, 0 as controller")
            ->select();
        foreach( $onBand as $k=>$v ){
            $levelAttr = explode(',',$v['level']);
            $onBand[$k]['controller'] = ChineseToPY($v['pay_name']);
            unset($onBand[$k]['level']);
            if( !in_array($level,$levelAttr) ) unset($onBand[$k]);
        }
        //线上支付宝或微信

        $onThird = Db::name("pay_xianshang")->where(['open'=>1,'is_code'=>1])->field("id,pay_name,level,0 as type_value,2 as method,0 as controller")->select();
        $hasUser = Db::name("code_account")->where(['method_id'=>$id])->group("type")->column("type,count(*) as num");
        foreach( $onThird as $k=>$v ){
            $user_key = $v['pay_name']=="微信扫码" ? "wechat" : 'alipay';
            if( !isset($hasUser[$user_key]) && empty($hasUser[$user_key]) ){
                unset($onThird[$k]);
                continue;
            }
            $levelAttr = explode(',',$v['level']);
            unset($onThird[$k]['level']);
            if( !in_array($level,$levelAttr) ) unset($onThird[$k]);
        }
        //线下支付
        $offThird = Db::name("pay_xxlist")->where(['method_id'=>$id])->field("id,xx_name as type_name,0 as type_value,xx_weixin,xx_zhifubao,xx_qq,xx_wangyin,3 as method,0 as controller")->select();
        foreach($offThird as &$v){
            if( 1==intval($v['xx_weixin']) ) $v['pay_name'] = '微信';
            if( 1==intval($v['xx_zhifubao']) ) $v['pay_name'] = '支付宝';
            if( 1==intval($v['xx_wangyin']) ) $v['pay_name'] = '银联';
            if( 1==intval($v['xx_qq']) ) $v['pay_name'] = 'QQ';
            unset($v['xx_weixin']);
            unset($v['xx_zhifubao']);
            unset($v['xx_wangyin']);
            unset($v['xx_qq']);
        }
        unset($v);
        $bank_list = array_merge($onBand,$onThird,$offThird);
        if( empty($bank_list) ) return json_encode(['status'=>0,'msg'=>'无支付信息']);
        $first_bank = array();
        if( !empty($bank_list) ){
            $first_bank = $bank_list[0];
        }
        return json_encode(['status'=>1,'list'=>$bank_list,'detail'=>$first_bank]);
    }
    /**
     * @Author
     * @Purpose 获取单个账户信息
     */
    public function getOfflineInfoOne()
    {
        $id_info = input('post.id') ? input('post.id') : '';
        $res = explode('_', $id_info);
        if (!isset($res[1])) return packJson('', '非法操作', 500);
        $id = $res[1];

        $data = Db::name('pay_xxlist')->where('id', $id)->find();
        if (!$data) return packJson('', '非法操作', 500);
        return packJson($data, '', 200);
    }

    /**
     * @Author
     * @Purpose 电脑版用户提现
     * @Time 2017-11-20
     */
    public function drawMoney()
    {
        //试玩账号无法提现
        if ($this->user_all['swzh'] == 1) {
            js_tishi('试玩账号无法提现！', '/index/User/index');
            exit;
        }

        //查询银行及提现信息
        $bank_list = Db::name('bank')->select();
        $many_user = Db::name('username')->where(array('username' => $this->user_all['username']))->find();
        $user_tx = $many_user['dml'] <= 0 ? $user_tx = $many_user['je'] : 0;
        if (empty($many_user['bankno'])) {
            js_tishi('请先到个人中心绑卡！', '/index/User/index');
            exit;
        }
        $tixian_tishi = Db::name('xt_tixian')->find();


        $time = strtotime('Y-m-d', time());
        $star = strtotime($time . ' 00:00:00');
        $end = strtotime($time . ' 23:59:59');
        $je = Db::name('tixian_list')->where(['username' => $this->user_all['username'], 'txtime' => ['between', $star . ',' . $end]])->select();
        $tx = 0;
        $cs = 0;
        foreach ($je as $v) {
            $tx += $v['txje'];
            $cs += 1;
        }
        $txlist = array();
        $txlist['tx'] = $tx;
        $txlist['cs'] = $cs;
        $this->assign('user_tx', $user_tx);
        $this->assign('txlist', $txlist);
        $this->assign('many_user', $many_user);
        $this->assign('current', 'draw');
        $this->assign('bank_qidunu', $bank_list);
        $this->assign('tixian_tishi', $tixian_tishi);
        return $this->fetch('caiwu_tx');
    }

    public function service()
    {
        $source = input('get.source') < 3 && !empty(input('get.source')) ? input('get.source') : 1;
        $wxAndqq = array(
            1 => 'qq',
            2 => 'wx'
        );
        //判断是否有文件，如果没有，添加一个文件
        foreach ($wxAndqq as $v) {
            if (is_file(ROOT_PATH . '/logs/service_yk_' . $v . '.txt') !== true) {
                file_put_contents(ROOT_PATH . '/logs/service_yk_' . $v . '.txt', '0');
            } else if (is_file(ROOT_PATH . '/logs/service_hy_' . $v . '.txt') !== true) {
                file_put_contents(ROOT_PATH . '/logs/service_hy_' . $v . '.txt', '0');
            }
        }
        //查询当前账号是不是试玩
        $user_type = Db::name('username')->where(['username' => input('cookie.username')])->field('swzh')->find();
        if ($user_type['swzh'] == 1 || $user_type['swzh'] === '') {
            $type = $source == 1 ? 0 : 2;
        } else {
            $type = $source == 1 ? 1 : 3;
        }
        //当前客服账号总数
        $service_count = Db::name('xt_kflink')->where(['type' => $type, 'status' => 1])->field('id')->count();
        $file = file_get_contents(ROOT_PATH . '/logs/service_yk_' . $wxAndqq[$source] . '.txt');
        if ($file >= $service_count) {
            $file = 0;
        }

        file_put_contents(ROOT_PATH . '/logs/service_yk_' . $wxAndqq[$source] . '.txt', $file + 1);
        $file = file_get_contents(ROOT_PATH . '/logs/service_yk_' . $wxAndqq[$source] . '.txt');

        //查询所有客服
        $service = Db::name('xt_kflink')->where(['type' => $type, 'status' => 1])->field('qq')->select();
        $qq = array();
        foreach ($service as $key => $val) {
            $qq[$key + 1] = $val['qq'];
        }

        $service_num = isset($qq[$file]) ? $qq[$file] : '暂无号码';
        //打开QQ窗口
        //QQ需要设置接受临时会话
        if (input('get.mobile') == 1) {
            return $service_num;
        } else {
            $this->redirect('http://wpa.qq.com/msgrd?v=3&amp&uin=' . $service_num . '&amp&site=qq&amp&menu=yes');
        }
    }


    /**
     * @Author
     * @Purpose 电脑版用户修改密码
     * @Time 2017-11-17
     */
    public function updatePass()
    {
        $this->assign('current', 'accountInfo');
        return $this->fetch('update_pass');
    }

    /**
     * @Author
     * @Purpose 电脑版用户下注记录
     * @Time 2017-11-17
     */
    public function callRecord()
    {
        //接收所需参数
        $tzid = input('tzid') ? input('tzid') : '';
        $czid = input('czid') ? input('czid') : '';
        $classtz = input('classtz') ? input('classtz') : '0';
        $timebh = input('timebh') ? input('timebh') : '1';
        $page = input('page') ? input('page') : 1;
        if ($page < 1) $page = 1;
        $page_num = 10;
        /* ------------------------------------------------投注记录详情----------------------------------------------- */
        if ($tzid && $czid) {
            if ($this->user_all['nbzh'] == 1 || $this->user_all['swzh'] == 1) {
                $yxsql_mysq = "touzhu_list_sw";
            } else {
                $yxsql_mysq = "touzhu_list_ok";
            }
            //正常的订单
            $dingdan = Db::name('touzhu_list_no')->where(['id' => $tzid, 'username' => $this->user_all['username'], 'czid' => $czid])->find();
            $dingdanzt = '正常';
            if (!$dingdan) {
                $dingdan = Db::name($yxsql_mysq)->where(['id' => $tzid, 'username' => $this->user_all['username'], 'czid' => $czid])->find();
            }
            //追号的订单
            if (!$dingdan) {
                $dingdan = Db::name('touzhu_list_zh')->where(['id' => $tzid, 'username' => $this->user_all['username'], 'czid' => $czid])->find();
                $dingdanzt = '追号';
            }
            if (empty($dingdan)) {
                $this->redirect('/index/User/callRecord');
            }
            $cnzmshdui = Db::name('caipai_list')->where('id', $czid)->find();
            if ($cnzmshdui['cp_name_new'] == '') $cnzmshdui['cp_name_new'] = $cnzmshdui['cp_name_old'];
            //投注规格
            if ($dingdan['nbzh'] == 1) $tzmss = '元';
            if ($dingdan['nbzh'] == 2) $tzmss = '角';
            if ($dingdan['nbzh'] == 3) $tzmss = '分';
            //判断是否开奖
            if ($dingdan['kjjg'] < 1) {
                $dingdan['kjjg'] = ['未开奖'];
            } else {
                $dingdan['kjjg'] = kjjg_split($dingdan['kjjg'], $dingdan['czid']);
            }
            //获取开奖时间
            $dingdan['tz_time'] = date('Y-m-d H:i:s', $dingdan['tz_time']);
            //投注玩法
            if ($dingdan['wfid'] > 0) {
                $wfnames = Db::name('play_classify')->where('id', $dingdan['wfid'])->find();
            }
            if (!$wfnames['class_name_mini']) {
                $wfnames['class_name_mini'] = $dingdan['tzhm'];
            }
            if (!empty($wfnames['digit'])) {
                $dingdan['tzhm'] = digit($dingdan['tzhm'], $wfnames['digit'], $czid,$wfnames['id']);
            }
            $this->assign('cnzmshdui', $cnzmshdui);
            $this->assign('dingdan', $dingdan);
            $this->assign('wfnames', $wfnames);
            $this->assign('tzmss', $tzmss);
            $this->assign('dingdanzt', $dingdanzt);
            return $this->fetch('shop_detail');
            exit;
        }

        /* ------------------------------------------------投注记录列表----------------------------------------------- */

        $all_cz_list = Db::name('caipai_list')->where('cp_if_open', '<', 2)->select();
        $touzhu_all = $this->touzhuJilu($this->user_all['username'], $timebh, $czid, $classtz);
        if (count($touzhu_all) > 0) {
            $touzhu_all = multi_array_sort($touzhu_all, 'tz_time');
        }
        $youxiaoje = 0;
        foreach ($touzhu_all as $value){
        	$youxiaoje += $value['tzje'];
        }
        $zcount = count($touzhu_all);
        $zys = ceil($zcount / $page_num);
        if ($page > $zys) $page = $zys;
        $openjl = ($page - 1) * $page_num;
        $touzhu_all = array_slice($touzhu_all, $openjl, $page_num);
       
        $czids = '';
        $wfids = '';
        foreach ($touzhu_all as &$xh_1) {
            $czids .= $xh_1['czid'] . ',';
            $wfids .= $xh_1['wfid'] . ',';
            $xh_1['tz_time'] = date('Y-m-d H:i:s', $xh_1['tz_time']);
        }
		$this->assign('yxje',$youxiaoje);
        $this->assign('tzid', $tzid);
        $this->assign('czid', $czid);
        $this->assign('classtz', $classtz);
        $this->assign('timebh', $timebh);
        $this->assign('zongcount', $zcount);
        $this->assign('zys', $zys);
        $this->assign('page', $page);
        $this->assign('list_ca', $all_cz_list);
        $this->assign('touzhulist', $touzhu_all);
        return $this->fetch('shop_tz');
    }

    /**
     * @Author
     * @Purpose 电脑版提现记录
     * @Time 2017-11-18
     */
    public function drawMoneyRecord()
    {
        $page = input('page') ? input('page') : 1;
        $page_num = 10;
        //查询提现记录
        $tixianjl = $this->tixianjl($this->user_all['username']);
        //总页数
        $zcount = count($tixianjl);
        $zys = ceil($zcount / $page_num);
        //页数限制
        if ($page > $zys) $page = $zys;
        if ($page < 1) $page = 1;
        $offset = ($page - 1) * $page_num;
        //处理提现记录
        if (count($tixianjl) > 0) {
            $tixianjl = multi_array_sort($tixianjl, 'txtime');
        }
        $tixianjl = array_slice($tixianjl, $offset, $page_num);
        foreach ($tixianjl as &$xh_1) {
            if ($xh_1['zt'] == '1') $xh_1['zt'] = '成功';
            if ($xh_1['zt'] == '0') $xh_1['zt'] = '处理中';
            $xh_1['txtime'] = date('Y-m-d H:i:s', $xh_1['txtime']);
        }

        $this->assign('current', 'drawMoney');
        $this->assign('zys', $zys);
        $this->assign('zcount', $zcount);
        $this->assign('page', $page);
        $this->assign('touzhulist', $tixianjl);
        return $this->fetch('caiwu_txjl');
    }

    /**
     * @Author
     * @Purpose 电脑版充值记录
     * @Time 2017-11-18
     */
    public function rechargeRecord()
    {
        $page = input('page') ? input('page') : 1;
        $page_num = 10;

        $where = [
            'username' => $this->user_all['username'],
            'zt' => ['neq',9]
        ];

        //总页数
        $zcount = Db::name('chongzhi_list')->where($where)->count();
        $zys = ceil($zcount / $page_num);
        //页数限制
        if ($page > $zys) $page = $zys;
        if ($page < 1) $page = 1;
        //查询充值记录
        $offset = ($page - 1) * $page_num;
        $recharge = Db::name('chongzhi_list')->where($where)->field('ddbh,je,czclass,cztime,zt,xxbank')->order('cztime', 'DESC')->limit($offset, $page_num)->select();

        foreach($recharge as &$py) {
            $py['cztime'] = date('m-d H:i:s',$py['cztime']);
            if($py['czclass']==1) $py['czclass'] = $py['xxbank'];//线上
            if($py['czclass']==2) $py['czclass'] = $py['xxbank'].'(线下充值)';//线下
            if($py['czclass']==3) $py['czclass'] = '手工充值';
            if($py['zt'] == 1) {
                $py['zt'] = '已到账';
            }elseif($py['zt']== '-1') {
                $py['zt'] = '充值失败';
            }else{
                $py['zt'] = '处理中';
            }
        }
        unset($py);

        $this->assign('current', 'recharge');
        $this->assign('zys', $zys);
        $this->assign('zcount', $zcount);
        $this->assign('page', $page);
        $this->assign('touzhulist', $recharge);
        return $this->fetch('caiwu_cz');
    }

    /**
     * @Author
     * @Purpose 电脑版用户其他金额记录
     * @Time 2017-11-18
     */
    public function other()
    {
        $page = input('page') ? input('page') : 1;
        $page_num = 10;
        //查询总页数
        $zcount = Db::name('caijin_list')->where('username', $this->user_all['username'])->count();
        $zys = ceil($zcount / $page_num);
        //页数限制
        if ($page > $zys) $page = $zys;
        if ($page < 1) $page = 1;
        //查询彩金记录
        $offset = ($page - 1) * $page_num;
        $cj = Db::name('caijin_list')->field('cjje as je,beizhu as way,fstime as time')->where('username', $this->user_all['username'])->where('cjje','>','0')->order('fstime', 'DESC')->limit($offset, $page_num)->select();
        $fs = Db::name('fs_list')->field('fsje as je,"返水" as way,distribute_time as time')->where('username', $this->user_all['username'])->where('fsje','>','0')->order('distribute_time', 'DESC')->limit($offset, $page_num)->select();
        $agent = Db::name('agent_balance')->field('balance as je,"返佣" as way,add_time as time')->where('agent', $this->user_all['username'])->where('balance','>','0')->order('add_time', 'DESC')->limit($offset, $page_num)->select();
        $bonus = Db::name('bonus_user')->field('je,"红包" as way,time')->where('username', $this->user_all['username'])->where('je','>','0')->order('time', 'DESC')->limit($offset, $page_num)->select();
		$bk = Db::name('username')->field('reg_je as je,"绑卡彩金" as way,bk_time as time')->where('username',$this->user_all['username'])->where('reg_je','>','0')->select();
        $payjls = array_merge($bk,$cj, $fs, $agent, $bonus);
        if (isset($payjls[0])) {
            $payjls = arraySequence($payjls, 'time');
        }

        $this->assign('current', 'bounty');
        $this->assign('zys', $zys);
        $this->assign('zcount', $zcount);
        $this->assign('page', $page);
        $this->assign('touzhulist', $payjls);
        return $this->fetch();
    }

    /**
     * @Author
     * @Purpose 电脑版用户消息中心
     * @Time 2017-11-18
     */
    public function message()
    {
        //消息列表
        $xx_listdb = Db::name('xiaoxi')->where('username', $this->user_all['username'])->order('id', 'DESC')->limit(30)->select();

        $this->assign('current', 'message');
        $this->assign('xiaoxi_ls', $xx_listdb);
        return $this->fetch();
    }

    /**
     * 代理
     */
    public function dlCentent()
    {
        return $this->fetch('dailishuoming');
    }

    public function dailibaobiao()
    {
        $user = input('user', '');
        $time = input('time','today');
        
		$u = Db::name('username')->where('tjr',$this->user_all['username'])->column('username');

        if ($user != '' && in_array($user, $u)!==false) {
            $count = $this->dlXiaJiZongRenShu($user,$time);
            $counts = Db::name('username')->where('tjr',$user)->whereTime('reg_time',$time)->count();
            $yj = Db::name('agent_balance')->where('agent', $user)->whereTime('add_time',$time)->value('SUM(balance)');
        } else {
            $count = $this->dlXiaJiZongRenShu($this->user_all['username'],$time);
            $counts = Db::name('username')->where('tjr',$this->user_all['username'])->whereTime('reg_time',$time)->count();
            $yj = Db::name('agent_balance')->where('agent', $this->user_all['username'])->whereTime('add_time',$time)->value('SUM(balance)');
        }
        
        $this->assign('yj', sprintf('%.2f', $yj));
        $this->assign('count', $count);
        $this->assign('user', $user);
        $this->assign('time',$time);
        $this->assign('xxrenshu',$counts);
        $this->assign('day', input('day'));
        return $this->fetch();
    }
    public function xiajidailibaobiao()
    {
    	$user = input('user', '');
    	$time = input('time','today');
    	$u = Db::name('username')->where('tjr',$this->user_all['username'])->column('username');
    
    	if ($user != '') {
    		$count = $this->dlXiaJiZongRenShu($user,$time);
    		$count['xxrenshu'] = Db::name('username')->where('tjr',$user)->whereTime('reg_time',$time)->count();
    		$count['yj'] = Db::name('agent_balance')->where('agent', $user)->whereTime('add_time',$time)->value('SUM(balance)');
    	} else {
    		$count = $this->dlXiaJiZongRenShu($this->user_all['username'],$time);
    		$count['xxrenshu'] = Db::name('username')->where('tjr',$this->user_all['username'])->whereTime('reg_time',$time)->count();
    		$count['yj'] = Db::name('agent_balance')->where('agent', $this->user_all['username'])->whereTime('add_time',$time)->value('SUM(balance)');
    	}
    	if($count['yj']==null){
    		$count['yj']=0;
    	}
    	return json($count);
    }
    
    function dlXiaJiZongRenShu($user,$time)
    {
        static $count = 0;
        static $tzje = 0;
        static $zjje = 0;
        static $hdlj = 0;
        static $tzrs = 0;
        static $txje = 0;
        static $czje = 0;
        static $czrs = 0;
        static $tdye = 0;
        $dl = Db::name('username')->where('username', $user)->value('fandian');
        
        $us = Db::name('username')->field('username,dl,xjrens')->where('tjr', $user)->whereTime('reg_time',$time)->select();
        foreach ($us as $val) {
            $tdye += Db::name('username')->where('username', $val['username'])->whereTime('reg_time',$time)->value('je');
            $je = Db::name('touzhu_list_ok')->where('username', $val['username'])->whereTime('tz_time',$time)->value('SUM(tzje)');
            $tzje += $je;
            $cz = Db::name('chongzhi_list')->where(['username' => $val['username'], 'zt' => 1, 'czadmin' => ['<>', '']])->whereTime('cztime',$time)->value('SUM(je)');
            $czje += $cz;
            $txje += Db::name('tixian_list')->where(['username' => $val['username'], 'zt' => 1, 'shadmin' => ['<>', ''], 'czadmin' => ['<>', '']])->whereTime('txtime',$time)->value('SUM(txje)');
            $zjje += Db::name('touzhu_list_ok')->where('username', $val['username'])->whereTime('tz_time',$time)->value('SUM(zjje)');
            $hdlj += Db::name('caijin_list')->where('username', $val['username'])->whereTime('fstime',$time)->value('SUM(cjje)');
            if ($je) {
                $tzrs += 1;
            }
            if ($cz) {
                $czrs += 1;
            }
            if ($val['dl'] == 1) {
                $this->dlXiaJiZongRenShu($val['username'],$time);
            }
        }
        return array('fandian' => $dl, 'tdye' => $tdye, 'czje' => $czje, 'czrs' => $czrs, 'count' => $count, 'tzje' => $tzje, 'zjje' => $zjje, 'cjje' => $hdlj, 'tzrs' => $tzrs, 'txje' => $txje);
    }

    public function xiajibaobiao()
    {
        $username = input('post.user')?input('post.user'):'';
        $hhh = input('get.dl')?input('get.dl'):'';
        $u = input('get.user')?input('get.user'):'';
        $start = 0;
        $end = time();
        
        $time = [$start, $end];
        $page = input('page') ? input('page') : 1;
        $limit = 10;
        if ($username!='' || $u!='') {
        	if($username){
        		$hhh='';
        	}

        		$users = 1;
        		$zys = ceil($users/$limit);
        		if($page>=$zys){ $page=$zys;}
	        	
	        		if($hhh==2){
	        			$users = Db::name('username')->where(['tjr' => $u,'dl'=>1])->count();
	        			$zys = ceil($users/$limit);
	        			if($page>=$zys){ $page=$zys;}
	        			$user = Db::name('username')->where(['tjr' => $u,'dl'=>1])->page($page,$limit)->order('id','DESC')->select();
	        		}elseif($hhh==1){
	        			$users = Db::name('username')->where(['tjr' => $u,'dl'=>0])->count();
	        			$zys = ceil($users/$limit);
	        			if($page>=$zys){ $page=$zys;}
	        			$user = Db::name('username')->where(['tjr' => $u,'dl'=>0])->page($page,$limit)->order('id','DESC')->select();
	        		}else{
	            		$user = Db::name('username')->where(['username' => $username])->page($page,$limit)->order('id','DESC')->select();
	        		}

        	
        } else {
        	$users = Db::name('username')->where('tjr', $this->user_all['username'])->count();
        	$zys = ceil($users/$limit);
        	if($page>=$zys){ $page=$zys;}
            $user = Db::name('username')->where(['tjr' => $this->user_all['username']])->page($page,$limit)->order('id','DESC')->select();
        }
        $tzzh = 0;
        $zjzh = 0;
        $yjzh = 0;
        $czzh = 0;
        $txzh = 0;
        $xjzh = 0;
        $hyzh = 0;
        foreach ($user as &$v) {
            $xj = Db::name('username')->where(['tjr' => $v['username'], 'dl' => 1])->whereTime('reg_time', 'BETWEEN', $time)->value('COUNT(*)');
            $dlxj = Db::name('username')->where(['tjr' => $v['username'], 'dl' => 0])->whereTime('reg_time', 'BETWEEN', $time)->value('COUNT(*)');
            $yj = Db::name('agent_balance')->where('agent', $v['username'])->whereTime('add_time', 'BETWEEN', $time)->value('SUM(balance)');
            $tzje = Db::name('touzhu_list_ok')->field('SUM(tzje) as tzje,SUM(zjje) as zjje')->where('username', $v['username'])->whereTime('tz_time', 'BETWEEN', $time)->find();
            $cz = Db::name('chongzhi_list')->where(['username' => $v['username'], 'zt' => 1, 'czadmin' => ['<>', '']])->whereTime('cztime', 'BETWEEN', $time)->value('SUM(je)');
            $tx = Db::name('tixian_list')->where(['username' => $v['username'], 'zt' => 1, 'shadmin' => ['<>', ''], 'czadmin' => ['<>', '']])->whereTime('txtime', 'BETWEEN', $time)->value('SUM(txje)');
            $v['sy'] = sprintf('%.2f', $yj);
            $v['tz'] = sprintf('%.2f', $tzje['tzje']);
            $v['zj'] = sprintf('%.2f', $tzje['zjje']);
            $v['cz'] = sprintf('%.2f', $cz);
            $v['tx'] = sprintf('%.2f', $tx);
            $v['xjhy'] = $dlxj ? $dlxj : 0;
            $v['xjdl'] = $xj ? $xj : 0;
            $tzzh += $v['tz'];
            $zjzh += $v['zj'];
            $yjzh += $v['sy'];
            $czzh += $v['cz'];
            $hyzh += $v['xjhy'];
            $txzh += $v['tx'];
            $xjzh += $v['xjdl'];
        }
        if($page < 1) $page = 1;
        $this->assign('count',$users);
        $this->assign('zys',$zys);
        $this->assign('page',$page);
        $this->assign('h',$hhh);
        $this->assign('time', date('Y-m-d'));
        $this->assign('tz', $tzzh);
        $this->assign('zj', $zjzh);
        $this->assign('sy', $yjzh);
        $this->assign('cz', $czzh);
        $this->assign('xjhy', $hyzh);
        $this->assign('tx', $txzh);
        $this->assign('xjdl', $xjzh);
        $this->assign('u',$username);
        $this->assign('user', $user);
        return $this->fetch();
    }

    public function xiajikaihu()
    {
        if (input('number')) {
            $fandian = input('number');

            $yqm = $this->code();
            $u = Db::name('username')->where('username', $this->user_all['username'])->field('tjm,fandian')->find();
            $date = array('tjm' => $u['tjm'] . '|' . $yqm . '-' . $fandian);
            $res = Db::name('username')->where('username', $this->user_all['username'])->update($date);
            if ($res) {
                js_tishi('生成成功', 'xiajikaihu');
            } else {
                js_tishi('生成失败', 'xiajikaihu');
            }

        } else {
            $user = Db::name('username')->where('username', $this->user_all['username'])->find();
            $tjm = explode('|', $user['tjm']);
            $tjm_new = array();
            $tjm_old = '';
            foreach ($tjm as $v) {
                if (strpos($v, '-') !== false) {
                    $tjm_new[] = explode('-', $v);
                } else {
                    $tjm_old = $v;
                }
            }
            $ymxz = Db::name('dl_domain')->where('status', 1)->select();
            $this->assign('tjmold', $tjm_old);
            $this->assign('ymxz', $ymxz);
            $this->assign('tjm', $tjm_new);
            $this->assign('user', $user);
            return $this->fetch();
        }
    }

    public function xiajiguanli()
    {
        $username = input('user');
		$page = input('page')?input('page'):1;
		$limit = 10;
        if ($username) {
            $users = Db::name('username')->where(['tjr' => $username])->count();
            $zys = ceil($users/$limit);
            if($page>=$zys){ $page=$zys;}
            $user = Db::name('username')->where(['tjr' => $username])->page($page,$limit)->select();
        } else {
            $users = Db::name('username')->where('tjr', $this->user_all['username'])->count();
            $zys = ceil($users/$limit);
            if($page>=$zys){ $page=$zys;}
            $user = Db::name('username')->where('tjr', $this->user_all['username'])->page($page,$limit)->select();
        }
        foreach ($user as &$v) {
            $xj = Db::name('username')->where(['tjr' => $v['username'], 'dl' => 1])->value('COUNT(*)');
            $dlxj = Db::name('username')->where(['tjr' => $v['username'], 'dl' => 0])->value('COUNT(*)');
            $v['xjdl'] = $xj;
            $v['dlxj'] = $dlxj;
        }
        if($page < 1) $page = 1;
        $this->assign('count',$users);
        $this->assign('zys',$zys);
        $this->assign('page',$page);
        $this->assign('user', $user);
        return $this->fetch();
    }

    public function touzhumingxi()
    {
        $start = strtotime(date("Y-m-d",strtotime("-7 day")).' 00:00:00');
        $end = time();
        $caip = input('caizhong') ? input('caizhong') : 0;
        
        $user = input('user','');
        
        $time =[$start,$end];
        $touzhu = array('dkj' => [], 'yzj' => [], 'wzj' => []);
        $us = '';
        if ($user != '') {
            $tzmx = Db::name('username')->where('username', $user)->column('username');
        } else {
            $tzmx = Db::name('username')->where('tjr', $this->user_all['username'])->column('username');
        }
        $us = implode(',', $tzmx);
        if ($caip != 0) {
            $where['czid'] = $caip;
        } else {
            $where = array();
        }
        $kj = input('kj') ? input('kj') : '';
        if ($kj == '1' || $kj == '') {
            $touzhu['dkj'] = Db::name('touzhu_list_no')
                ->alias('a')
                ->join('__CAIPAI_LIST__ b', 'b.id=a.czid')
                ->join('__PLAY_CLASSIFY__ c', 'c.id=a.wfid')
                ->field("a.id as uid,a.czid,a.wfid,a.username,a.qihao,a.tzhm,a.tzje,a.tz_time,b.cp_name_old as cp_name_old,b.cp_name_new as cp_name_new,c.class_name_mini,'待开奖' as status")
                ->where('a.username', 'IN', $us)->where($where)->whereTime('a.tz_time', 'BETWEEN', $time)->select();
        }
        if ($kj == '3' || $kj == '1' || $kj == '') {
            $touzhu['wzj'] = Db::name('touzhu_list_ok')
                ->alias('a')
                ->join('__CAIPAI_LIST__ b', 'b.id=a.czid')
                ->join('__PLAY_CLASSIFY__ c', 'c.id=a.wfid')
                ->field("a.id as uid,a.czid,a.wfid,a.username,a.qihao,a.tzhm,a.tzje,a.tz_time,b.cp_name_old as cp_name_old,b.cp_name_new as cp_name_new,c.class_name_mini,'未中奖' as status")
                ->where('a.username', 'IN', $us)->where($where)->whereTime('a.tz_time', 'BETWEEN', $time)->where('a.zjje', '0')->select();
        }
        if ($kj == '2' || $kj == '1' || $kj == '') {
            $touzhu['yzj'] = Db::name('touzhu_list_ok')
                ->alias('a')
                ->join('__CAIPAI_LIST__ b', 'b.id=a.czid')
                ->join('__PLAY_CLASSIFY__ c', 'c.id=a.wfid')
                ->field("a.id as uid,a.qihao,a.czid,a.wfid,a.username,a.tzhm,a.tzje,a.tz_time,b.cp_name_old as cp_name_old,b.cp_name_new as cp_name_new,c.class_name_mini,'已中奖' as status")
                ->where('a.username', 'IN', $us)->where($where)->whereTime('a.tz_time', 'BETWEEN', $time)->where('a.zjje', '>', '0')->select();
        }
        $page = input('page')?input('page'):1;
        $count = count($touzhu['dkj'])+count($touzhu['wzj'])+count($touzhu['yzj']);
        $limit=10;
        $zys = ceil($count/$limit);
        if($page>$zys)$page=$zys;
        if($page<1)$page=1;
        $zong = array_merge($touzhu['dkj'],$touzhu['wzj'],$touzhu['yzj']);
        $this->assign('page',$page);
        $this->assign('zys',$zys);
        $this->assign('count',$count);
        $this->assign('limit',$limit);
        $caizhong = Db::name('caipai_list')->where('cp_if_open', 1)->select();
        $this->assign('kj', $kj);
        $this->assign('caip', $caip);
        $this->assign('caizhong', $caizhong);
        $this->assign('day', input('day'));
        $this->assign('touzhu', $zong);
        $this->assign('user', $user);
        return $this->fetch();
    }

    public function jiaoyimingxi()
    {

        $user = input('user','');
        $zhaiyao = input('zhaiyao') ? input('zhaiyao') : '';
            
        
        $start = strtotime(date("Y-m-d",strtotime("-7 day")).' 00:00:00');
        $end = strtotime(date('Y-m-d 23:59:59'),time());
        
        $time = [$start, $end];

        $jiaoyi = array(
            'chongzhi' => array(),
            'tixian' => array(),
            'tixianno' => array(),
        );
        if ($user != '') {
            $tzmx = Db::name('username')->where('username', $user)->column('username');
        } else {
            $tzmx = Db::name('username')->where('tjr', $this->user_all['username'])->column('username');
        }
        $us = implode(',', $tzmx);
        if( !empty($us) ){
            if ($zhaiyao == '') {
                $jiaoyi['chongzhi'] = Db::name('chongzhi_list')
                					->field('username,cztime,czclass,je,czhje,zt,xxbank')
                					->where('username', 'IN', $us)->where('zt','neq',9)->whereTime('cztime', 'BETWEEN', $time)->select();
            }elseif($zhaiyao == '1' || $zhaiyao == '2' || $zhaiyao == '3') {
                $jiaoyi['chongzhi'] = Db::name('chongzhi_list')
                						->field('username,cztime,czclass,je,czhje,zt,xxbank')
                						->where('username', 'IN', $us)->where('zt','neq',9)->where('czclass', $zhaiyao)->whereTime('cztime', 'BETWEEN', $time)->select();
            }
            foreach( $jiaoyi['chongzhi'] as &$py ) {
                if($py['czclass']==2) $py['xxbank'] = $py['xxbank'].'(线下充值)';//线下
                if($py['czclass']==3) $py['xxbank'] = '手工充值';
            }
            unset($py);
            if ($zhaiyao == '' || $zhaiyao == 5) {
                $jiaoyi['tixian'] = Db::name('tixian_list')
                					->field("username,txtime as cztime,'提现' as czclass,txje as je,txhje as czhje,zt,'提现' as xxbank")
                					->where('username', 'IN', $us)->whereTime('txtime', 'BETWEEN', $time)->select();
            }
            if ($zhaiyao == '' || $zhaiyao == 4) {
                $jiaoyi['tixianno'] = Db::name('tixian_list_no')
                    ->alias('a')
                    ->join('__USERNAME__ b', 'b.username=a.username')
                    ->field("a.username,a.txtime as cztime,'提现退回' as czclass,a.txje as je,b.je as czhje,'提款失败' as zt,'提现退回' as xxbank")
                    ->where('a.username', 'IN', $us)->whereTime('a.txtime', 'BETWEEN', $time)->select();
            }
        }
        $page = input('page')?input('page'):1;
        $count = count($jiaoyi['chongzhi'])+count($jiaoyi['tixian'])+count($jiaoyi['tixianno']);
        $limit=10;
        $zys = ceil($count/$limit);
        if($page>$zys)$page=$zys;
        if($page<1)$page=1;
        $zong = array_merge($jiaoyi['chongzhi'],$jiaoyi['tixian'],$jiaoyi['tixianno']);
        array_multisort(array_column($zong,'cztime'),SORT_DESC,$zong);
        $this->assign('page',$page);
        $this->assign('zys',$zys);
        $this->assign('count',$count);
        $this->assign('limit',$limit);
        $this->assign('zhaiyao', $zhaiyao);
        $this->assign('day', input('day'));
        $this->assign('jiaoyi', $zong);
        $this->assign('user', $user);
        $this->assign('start', date('Y-m-d',$start));
        $this->assign('end', date('Y-m-d',$end));
        $this->assign('time', date('Y-m-d'));
        return $this->fetch();
    }
    
    public function djsm()
    {

       $usclass = Db::name('us_class')->order("czl asc")->select();
      foreach ($usclass as &$v){
          $v['fsbl']=floatval($v['fsbl']);
          $v['czzsbl']=floatval($v['czzsbl']);
          $v['czl']=floatval($v['czl']);
          $v['xml']=floatval($v['xml']);
          $v['dividend']=floatval($v['dividend']);
          $v['mearmoney']=floatval($v['mearmoney']);
          $v['zxtzxd']=floatval($v['zxtzxd']);
          $v['zdtzxd']=floatval($v['zdtzxd']);
      }
		$this->assign('usclass',$usclass);
        return $this->fetch();
    }

    /**
     * 监测用户是否存在
     */
    public function registerExist()
    {
        $reg_user = input('post.reg_user') ? input('post.reg_user') : '';
        if ($reg_user) {
            $reg_user = strtolower($reg_user);
            //验证是否用户名已注册
            $search_user = Db::name('username')->where('username', $reg_user)->count();
            if ($search_user > 0) {
                $this->error('抱歉，用户名已被占用');
            } else {
                $this->success('该用户可用');
            }
        } else {
            $this->error('抱歉，用户名不能为空');
        }
    }

    /**
     * @Author
     * @Purpose 注册验证
     * @Time 2017-11-16
     */
    public function register()
    {
        $reg_user = input('post.reg_user') ? input('post.reg_user') : '';
        $reg_pass = input('post.reg_pass') ? input('post.reg_pass') : '';
        $phone = input('post.reg_phone') ? input('post.reg_phone') : '';
        if ($reg_user) {
            $reg_user = strtolower($reg_user);
            //验证是否用户名已注册
            $search_user = Db::name('username')->where('username', $reg_user)->count();
            if ($search_user > 0) {
                $this->error('抱歉，用户名已被占用');
            }
        }
        if ($reg_user && $reg_pass/*  && $phone */) {
            $code = input('post.code') ? input('post.code') : '';
            $reg_recommend = input('post.reg_recommend') ? input('post.reg_recommend') : '';
            //判断是否需要验证验证码
            $codeif = Db::name('xt_reg')->find();
            if ($codeif['codo_open'] == 1) {
                if (!$code) {
                    $this->error('验证码错误');
                }
                if (!captcha_check($code)) {
                    $this->error('验证码错误');
                }
            }
            //判断推荐码是否有效
            $agent = '';
            $arr = array('id' => 0, 'username' => '', 'recommend' => ['0' => '', '1' => 0]);
            $tjm_open = $codeif['tjr_open'];

            if ($reg_recommend) {
                $dl = Db::name('username')->field('username,tjm,id')->where(['dl' => 1, 'tjm' => ['<>', '']])->select();
                foreach ($dl as $val) {
                    if (strpos($val['tjm'], $reg_recommend) !== false) {
                        $arr['username'] = $val['username'];
                        $arr['id'] = $val['id'];
                        $val['tjm'] = explode('|', $val['tjm']);
                        foreach ($val['tjm'] as $value) {
                            if (strpos($value, $reg_recommend) !== false) {
                                if (strpos($value, '-') !== false) {
                                    $arr['recommend'] = explode('-', $value);
                                } else {
                                    $arr['recommend'][0] = $value;
                                    $arr['recommend'][1] = 0;
                                }
                            }
                        }
                    }
                }
                if ($arr['recommend'][0] != $reg_recommend) {
                    $this->error('推荐码无效！');
                }
            } elseif (1 == intval($tjm_open)) {
                $this->error('推荐码必填！');
            }
            //解析IP
            /* $position = '';
            $ip = @file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip={$this->login_ip}");
            if ($ip > 0) {
                $ip = json_decode($ip, true);
                if ($ip['region'] && $ip['city']) {
                    $position = $ip['region'] . ' ' . $ip['city'];
                } else {
                    $position = $ip['country'];
                }
            } */
            //注册防骚扰
            $ruzhuc = Db::name('xt_zcfsr')->find();
            if ($ruzhuc['open'] == 1) {
                $ntimess = strtotime(date('Y-m-d') . ' 00:00:00');
                $zcount = Db::name('username')->where("reg_ip='{$this->login_ip}' AND reg_time>'{$ntimess}' ")->count();
                if ($zcount >= $ruzhuc['one_day_count']) {
                    $this->error('对不起您今天注册的会员账号过多！');
                }
            }

            //是否开启注册送金额
            $t = Db::name('xt_caijin')->where('id', 1)->find();
            if ($t['open'] == 1) {
                $je = $t['je'];
                $dml = $t['cj_dml'];
            } else {
                $je = 0;
                $dml = 0;
            }
            //将用户信息插入表
            $reg_pass = md5($reg_pass);
            $ntime = time();
            $login_key = suiji_zifu(15);

            model('Username')->setNewUser($arr['id'], $dml, $reg_user, $reg_pass, $arr['username'], $je, $ntime, $this->login_ip, '', 1, 'pc', 0, 1, $login_key);
            $data['mobile'] = $phone;
            $data['zcjje'] = $je;
            $data['reg_je'] = $je;
            if ($arr['recommend'][1] > 0) {
                $data['dl'] = 1;
                $data['dl_time'] = time();
                $data['tjm'] = $this->code();
                $data['fandian'] = $arr['recommend'][1];
            }
            Db::name('username')->where('username', $reg_user)->update($data);
            Db::name('username')->where('username',$reg_user)->setInc('login_num');
            if ($je > 0) {
                $this->state->UserFaSong($reg_user, "您注册账号赠送：" . $je . "元。已到账，请注意查收！");
                $data = array(
                    'username'=>$reg_user,
                    'user_class'=>1,
                    'cjje'=>$je,
                    'fstime'=>time(),
                    'beizhu' => '系统赠送，电脑端用户注册，赠送彩金',
                    'czadmin' => '系统赠送',
                    'cjhje'=>$je,
                );
                Db::name('caijin_list')->insert($data);
            }
            //标记用户为登录状态
            cookie("username", $reg_user);
            cookie("password", $reg_pass);
            cookie("login_key", $login_key);
            Cookie::delete('vip');
            $zx_list = Db::name('zaixian')->where('username', $reg_user)->find();
            if ($zx_list['id'] > 0) {
                //更新在线时长
                model('Zaixian')->updateOnlineTime($zx_list['id'], $reg_user, $ntime, 0, $this->login_ip, $this->fwurl);
            } else {
            	
                //设置在线时长
                model('Zaixian')->setOnlineTime($reg_user, $ntime, 0, $this->login_ip, $this->fwurl);
            }
            $this->success('注册成功!', '/index/Index/home');
        }
    }
public function changeHeader(){
        $img = isset($_POST['img'])? $_POST['img'] : '';
        // 获取图片
        list($type, $data) = explode(',', $img);
        // 判断类型
        $ext = '';
        if(strstr($type,'image/jpeg')!=''){
            $ext = '.jpg';
        }elseif(strstr($type,'image/gif')!=''){
            $ext = '.gif';
        }elseif(strstr($type,'image/png')!=''){
            $ext = '.png';
        }
        $base_path = ROOT_PATH.'public'.DS.'uploads'.DS.'avatar'.DS; //存放目录
        if(!is_dir($base_path)){
            @mkdir($base_path,0777,true);
        }
        // 生成的文件名
        $photo = time().$ext;
        $orgImg = Db::name('username')->where(['username'=>$this->user_all['username']])->value("img");
        if( @file_put_contents($base_path.$photo, base64_decode($data), true) && Db::name('username')->where(['username'=>$this->user_all['username']])->update(['img'=>basename( $photo )]) ){
            if( !empty($orgImg)) @unlink($base_path.$orgImg);
            return 1;
        }
        return 0;
    }
    /**
     * @Author
     * @Purpose 活动大厅领取奖励
     * @Time 2017-11
     */
    public function getAward()
    {
        //开启事务
        Db::startTrans();
        $hdid = input('post.hdid');
        $hdid = isset($hdid) ? $hdid : 0;
        $hdtime=0;
        $hdtime_1=0;
        if ($this->user_all['id'] > 0) {
            if (!$hdid) {
                return '请选择正确活动！';
            }
            $hdschsf = Db::name('xt_zzhd')->where('id', $hdid)->find();
            
            $hdschsf['tj_czje'] = explode('-', $hdschsf['tj_czje']);
            $hdschsf['tj_tzje'] = explode('-', $hdschsf['tj_tzje']);
            $hdschsf['hd_je'] = explode('-', $hdschsf['hd_je']);
            $hdschsf['tj_czje']=array_filter($hdschsf['tj_czje']);
            $hdschsf['tj_tzje']=array_filter($hdschsf['tj_tzje']);
            $hdschsf['hd_je']=array_filter($hdschsf['hd_je']);
            
            if ($hdschsf['id'] < 1) {
                return '请选择正确活动！';
            }
            //处理日期
            if ($hdschsf['tjzq'] == '1') {
                $year_now = date('Y-m-d', strtotime('-1 day')) . " 00:00:00";
                $year_now_1 = date('Y-m-d', strtotime('-1 day')) . " 23:59:59";
                $hdtime_1 = strtotime($year_now_1);
                $hdtime = strtotime($year_now);
                $taday = date('Y-m-d') . "00:00:00";
                $taday = strtotime($taday);
            }
            if ($hdschsf['tjzq'] == '2') {
                $year_now = date('Y-m-d', strtotime('-1 week last monday')) . "-01 00:00:00";
                $year_now_1 = date('Y-m-d', strtotime('last sunday')) . " 23:59:59";
                $hdtime_1 = strtotime($year_now_1);
                $hdtime = strtotime($year_now);
                $taday = date('Y-m-d', strtotime('sunday -6 day')) . " 00:00:00";
                $taday = strtotime($taday);
            }
            if ($hdschsf['tjzq'] == '3') {
                $year_now = date('Y-m', strtotime('-1 month')) . "-01 00:00:00";
                $year_now_1 = date('Y-m') . "-01 00:00:00";
                $hdtime_1 = strtotime($year_now_1);
                $hdtime = strtotime($year_now);
                $taday = date('Y-m') . "-01 00:00:00";
                $taday = strtotime($taday);
            }
            //取充值
            $czjes = 0;
            $chongzhije = Db::name('chongzhi_list')->where("username='{$this->user_all["username"]}' AND cztime>'{$hdtime}' AND cztime<'{$hdtime_1}' AND zt=1 ")->select();
            foreach ($chongzhije as $v) {
                $czjes = $czjes + $v['je'];
            }
            $czjes = floor($czjes);
            $k = '';
           
            if ($czjes < min($hdschsf['tj_czje'])) {
            	return "对不起，您没有达到领取条件！";
            }else{
	            foreach ($hdschsf['tj_czje'] as $key=>$it){
	            	if($it!= ''){
		            	if ($czjes >= $it) {
		            		$k = $key;
		            	}
	            	}
	            }
            }
            
        
            //取投注
            $tzje = 0;
            $chongzhije = Db::name('touzhu_list_ok')->where("username='{$this->user_all["username"]}' AND tz_time>'{$hdtime}' AND tz_time<'{$hdtime_1}' ")->select();
            foreach ($chongzhije as $v) {
                $tzje = $tzje + $v['tzje'];
            }
            $tzje = floor($tzje);
            $p = '';
            if ($tzje < min($hdschsf['tj_tzje'])) {
                return "对不起，您没有达到领取条件！";
            }else{
            	foreach ($hdschsf['tj_tzje'] as $key=>$it){
            		if($it!= ''){
	            		if ($tzje >= $it) {
	            			$p = $key;
	            		}
            		}
            	}
            }
            
            //查询是否已经领取
            $iflingq = Db::name('caijin_list')->where("username='{$this->user_all["username"]}' AND zzhdid='{$hdschsf["id"]}' AND fstime>='{$taday}' ")->find();
            if ($iflingq['id'] > 0) {
                return "您已经领取过了！";
            }
            //事务操作
            try {
                //插入彩金表并更新用户余额
                $m = [$k,$p];
                model('CaijinList')->setActivityMoney($this->user_all['username'], $this->user_all['us_class'], $hdschsf['hd_je'][min($m)], time(), '系统赠送，活动大厅领取奖励', '系统赠送', $hdschsf['id'], $this->user_all["je"]);
                Db::name('username')->where('id', $this->user_all['id'])->setInc('je', $hdschsf['hd_je'][min($m)]);
                Db::name('username')->where('id', $this->user_all['id'])->setInc('zcjje', $hdschsf['hd_je'][min($m)]);
                // 提交事务
                Db::commit();
                return 1;
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return "领取失败！";
            }
        } else {
            return "请登录会员账号再进行领取！";
        }
    }

    function code()
    {
        $code = rand('000000', '999999');
        
        /* for ($i = 1; $i <= 2; $i++) {
            $code .= chr(rand(97, 122));
        }
        for ($i = 1; $i <= 1; $i++) {
            $code .= chr(rand(65, 90));
        }
        for ($i = 1; $i <= 1; $i++) {
            $code .= chr(rand(97, 122));
        }
        for ($i = 1; $i <= 4; $i++) {
            $code .= chr(rand(65, 90));
        }
        for ($i = 1; $i <= 2; $i++) {
            $code .= chr(rand(97, 122));
        }
        for ($i = 1; $i <= 3; $i++) {
            $code .= chr(rand(65, 90));
        } */
        if ($code != '') {
            $yzm = Db::name('username')->where('dl', 1)->field('tjm')->select();
            $tjm = '';
            foreach ($yzm as $v) {
                $tjm .= $v['tjm'] . '--';
            }
            if (strstr($tjm, $code) !== false) {
                $this->code();
            }
        }
        return $code;
    }

}
